﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace BneyBaruch.Ingest.Core.WorkflowCommunication.Tracking
{
    [ServiceBehavior
        (
            InstanceContextMode = InstanceContextMode.Single,
            ConcurrencyMode = ConcurrencyMode.Reentrant
        )
    ]
    public class WorkflowTrackingService : IWorkflowTrackingService
    {
        #region Fields

        private List<IWorkflowTrackingServiceCallback> _subscribedCallers = new List<IWorkflowTrackingServiceCallback>();

        #endregion

        #region IWorkflowTrackingService Members

        public void SubscribeToWorkflowTrackingEvents()
        {
            IWorkflowTrackingServiceCallback caller = OperationContext.Current.GetCallbackChannel<IWorkflowTrackingServiceCallback>();
            if (!_subscribedCallers.Contains(caller))
            {
                _subscribedCallers.Add(caller);
            }
        }

        public void PublishTrackRecordEvent(WorkflowTrackRecordEvent workflowTrackRecordEvent)
        {
            if (_subscribedCallers != null && _subscribedCallers.Count > 0)
            {
                foreach (IWorkflowTrackingServiceCallback subscriber in _subscribedCallers)
                {
                    subscriber.NotifyTrackRecordEvent(workflowTrackRecordEvent);
                }
            }
        }

        #endregion
    }
}
